package com.example.beikeyigou.goods;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.beikeyigou.R;
import com.example.beikeyigou.utils.URLUtils;
import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * 编写listview和gridview适配器的过程
 * 1.创建一个类，继承与baseAdapter
 * 2.重写4个方法
 * 3.在类当中定义2个成员变量：context和集合
 * 4.创建构造方法，将两个成员变量赋值
 * 5.前三个方法按照套路写（固定写法）
 * 6.创建内部类，在内部类当中声明item布局对应控件，并在构造方法当中查找，构造方法要传view
 */
public class GoodsTypeAdapter extends BaseAdapter {
    Context context;
    List<GoodsBean.DataBean> data;
    int clickPos;

    public GoodsTypeAdapter(Context context, List<GoodsBean.DataBean> data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        VH vh = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_goodstype, parent, false);
            vh = new VH(convertView);
            convertView.setTag(vh);
        } else {
            vh = (VH) convertView.getTag();
        }
        GoodsBean.DataBean dataBean = data.get(position);
        vh.titleTv.setText(dataBean.getName());
        vh.desTv.setText(dataBean.getInfo());
        vh.priceTv.setText("￥" + dataBean.getPrice());
        String photo = dataBean.getPhoto();
        if (!TextUtils.isEmpty(photo)) {
            String photoUrl = URLUtils.PUBLIC_URL + photo;
            Picasso.with(context).load(photoUrl).into(vh.iv);
        }
        return convertView;
    }

    // 设置被点击的位置
    public void setClickPos(int clickPos) {
        this.clickPos = clickPos;
        notifyDataSetChanged();
    }

    class VH {
        TextView titleTv, priceTv, desTv;
        ImageView iv;

        public VH(View v) {
            titleTv = v.findViewById(R.id.item_goodsType_tv_title);
            priceTv = v.findViewById(R.id.item_goodsType_tv_price);
            desTv = v.findViewById(R.id.item_goodsType_tv_des);
            iv = v.findViewById(R.id.item_goodsType_tv_img);
        }
    }
}
